package com.aica.service.impl;


import com.aica.bo.UserAndRoleBo;
import com.aica.constant.StringBuilderConstant;
import com.aica.service.MyUserDetailsService;
import com.aica.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 重写登录认证方法
 * @author by
 * @date 2021/6/8
 */
@Slf4j
@Service
public class MyUserDetailsServiceImpl implements MyUserDetailsService {

    @Autowired
    private UserService userService;

    /**
     * 重写UserDetailsService里的登录认证程序
     * @param s 登录接口中捕获的username
     * @return 封装的用户信息
     * @throws UsernameNotFoundException 未找到用户名
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //这个if理论上不可达
        if(StringUtils.isEmpty(s) ){
            //return null;
            //日志打印
            log.info("登录失败，用户名不能为空");
            throw new UsernameNotFoundException("登录失败，用户名不能为空");

        }

        //TODO 查询数据库的用户信息和角色信息
        UserAndRoleBo userAndRoleBo = userService.selectUserAndRoleByUsername(s);

        //用户名不存在
        if(userAndRoleBo==null){
            //日志打印
            log.info("登录失败，未找到对应用户名："+s);
            //这里的msg描述信息没使用上
            throw new UsernameNotFoundException("登录失败，未找到对应用户名");
        }

        //处理自己的用户对象封装成UserDetails
        return new org.springframework.security.core.userdetails.User(
                userAndRoleBo.getUsername(),
                userAndRoleBo.getPassword(),
                getAuthority(userAndRoleBo.getRoleIds())
        );
    }

    /**
     * 返回一个List集合，集合中装入的是角色描述
     * @param roleIds 用户的角色id集合
     * @return 封装的SimpleGrantedAuthority认证集合
     */
    @Override
    public List<SimpleGrantedAuthority> getAuthority(List<Integer> roleIds) {

        List<SimpleGrantedAuthority> list = new ArrayList<>();

        //打印角色id集合
        roleIds.forEach(s-> System.out.print(s.toString() + " "));
        System.out.println();

        for (Integer roleId :roleIds) {
            //使用 用户等级进行拼接
            list.add(new SimpleGrantedAuthority(StringBuilderConstant.ROLE_ + roleId));
        }

        return list;
    }
}
